package demo.practice.dp;

public class P152_2 {
    public static void main(String[] args) {
        P152_2 p152_2= new P152_2();
        p152_2.maxProduct(new int[]{2,3,-2,4,-1});
    }

    public int maxProduct(int[] nums) {

        // [2,3,-2,4,-1]
        // dp[0]= 2     dp_min[0]=2
        // dp[1]= 6     dp_min[1]=6
        // dp[2]= -2    dp_min[2]=-2x dp[1] =-24
        // dp[3]= 4     p_min[3]= dp_min[2]xnums[3]=-24x4
        // dp[4]= p_min[3]xnums[4]  p_min[4]=dp[3]xnums[4]

        int[] dp_min = new int[nums.length];
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        dp_min[0] = nums[0];


        for (int i = 1; i < nums.length; i++) {
                int cur = nums[i];
                if (cur == 0) {
                dp_min[i] = 0;
                dp[i] = 0;
            } else if (cur > 0) {
                dp_min[i] = dp_min[i - 1] * nums[i];
                if (dp[i - 1] > 0) {
                    dp[i] = dp[i - 1] * nums[i];
                } else {
                    dp[i] = nums[i];
                }
            } else {
                //当前值 cur < 0
                if (dp_min[i - 1] > 0) {
                    dp_min[i] = dp_min[i - 1] * nums[i];
                } else {
                    dp_min[i] = Math.min(dp[i - 1] * nums[i], nums[i]);
                }

                if (dp_min[i - 1] > 0) {//前面没有负数可以 和当前的数相乘
                    dp[i] = nums[i];
                } else {
                    dp[i] = nums[i] * dp_min[i - 1];
                }
            }
        }

        int max = nums[0];
        for (int i = 0; i < nums.length; i++) {
            max = Math.max(dp[i], max);
        }
        return max;
    }
}
